﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;
using System.Globalization;

namespace Utils.MVC
{
    public static class HtmlHelperExtension
    {
        public static string Upload(this HtmlHelper htmlHelper,string name,string url,string buttonText,string ext,string errMes,string fileUrl)
        {
            var html = "";
            if (!string.IsNullOrEmpty(fileUrl))
            {
                string imgExt = "jpg|jpeg|bmp|gif|png|ico";
                string htmlt = "<a href='{0}'>{1}</a>";
                if (imgExt.Contains(fileUrl.Substring(fileUrl.LastIndexOf(".") + 1).Trim()))
                {
                    htmlt = "<img src='{0}' alt='{1}' />";
                }
                html = string.Format(htmlt, fileUrl, name);
            }
            string t =
                @"
                    <input id='{0}b' type='button' value='{3}' />
                    <input id='{0}' name='{0}' type='hidden' value='{6}' />
                    <div id='{0}r'>{5}</div>
                    <script type=""text/javascript"">
                    $(document).ready(function() {{
                            new AjaxUpload('#{0}b', {{
                                    action: '{1}',
                                    responseType: ""html"",
                                    onSubmit: function(file, ext) {{
                                    if (!(ext && /^({2})$/.test(ext))) {{
                                            alert('{4}');
                                            return false;
                                        }}
                                    }},
                                    onComplete: function(file, response) {{
                                    var fileInfo = FileInfo(response);
                                        if (fileInfo.Success) {{
                                            $(""#{0}"").val(fileInfo.Url);
                                            $(""#{0}r"").html(fileInfo.Html);
                                        }}
                                        else {{
                                            alert(fileInfo.Mes);
                                        }}
                                    }}
                                }});
                            }});
                    </script>
                    ";
            return string.Format(t, name, url, ext,buttonText, errMes,html,fileUrl);
        }
        public static string Upload(this HtmlHelper htmlHelper, string name, string url, string buttonText, string ext, string errMes)
        {
            return Upload(htmlHelper, name, url,buttonText, ext,  errMes, "");
        }


        public static string CheckBoxList<T>(this HtmlHelper htmlHelper, string name, IEnumerable<T> data, string TexeField, string ValueField, IDictionary<int,bool> SelectedValue, IDictionary<string, object> htmlAttributes)
        {

            if (data == null || data.Count() == 0)
                return "";

            bool select = false;
            var selectValueDic = new Dictionary<string, bool>();
            if (SelectedValue != null && SelectedValue.Count() > 0)
            {
                select = true;
                foreach (KeyValuePair<int, bool> pair in SelectedValue)
                {
                    selectValueDic.Add(pair.Key.ToString(),pair.Value);
                }
            }
            StringBuilder sb=new StringBuilder();
            for (int i = 0; i < data.Count(); i++)
            {
                TagBuilder divTagBuilder = new TagBuilder("div");
                divTagBuilder.MergeAttributes(htmlAttributes);

                TagBuilder checkBox=new TagBuilder("input");
                checkBox.MergeAttribute("type",HtmlHelper.GetInputTypeString(InputType.CheckBox));
                checkBox.MergeAttribute("name",name,true);
                checkBox.MergeAttribute("id",string.Format("{0}-{1}",name,i));
                var value = Eval(data.ElementAt(i), ValueField);
                checkBox.MergeAttribute("value",value);
                if(select&&selectValueDic.Keys.Contains(value)&&selectValueDic[value])
                    checkBox.MergeAttribute("checked","checked");

                TagBuilder label=new TagBuilder("label");
                label.MergeAttribute("for", string.Format("{0}-{1}", name, i));
                label.SetInnerText(Eval(data.ElementAt(i),TexeField));

                sb.Append(divTagBuilder.ToString(TagRenderMode.StartTag));
                sb.Append(checkBox.ToString(TagRenderMode.SelfClosing));
                sb.Append(label.ToString(TagRenderMode.Normal));
                sb.Append(divTagBuilder.ToString(TagRenderMode.EndTag));
            }
            return sb.ToString();
        }

        private static string Eval(object container, string expression)
        {
            object value = container;
            if (!String.IsNullOrEmpty(expression))
            {
                value = DataBinder.Eval(container, expression);
            }
            return Convert.ToString(value, CultureInfo.CurrentCulture);
        }
    }
}
